package handler

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"path"
	"yzy6.26exam/pkg"
)

func Upload(context *gin.Context) {
	file, m, err := context.Request.FormFile("file")
	if err != nil {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    204,
			"message": "解析失败",
			"data":    err.Error(),
		})
		return
	}
	ext := path.Ext(m.Filename)
	if ext != ".jpg" && ext != ".png" && ext != ".jpeg" && ext != ".gif" && ext != ".mp4" {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    203,
			"message": "文件格式错误",
			"data":    ext,
		})
		return
	}
	if (ext != ".mp4" && m.Size > 2<<20) || m.Size > 512<<20 {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    202,
			"message": "文件过大",
			"data":    m.Size,
		})
		return
	}
	upload, err := pkg.Upload(file, m)
	if err != nil {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    201,
			"message": "上传失败",
			"data":    err,
		})
		return
	}
	context.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "上传成功",
		"data":    upload,
	})
}
